<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of QualityAbnormal
 *
 * @author zhangxuelin
 */
class QualityAbnormal extends CI_Controller{
    //put your code here
    function __construct() {
        parent::__construct();
    }
    
    public function index($userid){
        //$userid= "6522";
        header("Access-Control-Allow-Origin:*");
        $username = $this->getUsername($userid);
        $makeDate = date("Y-m-d",  time());
        $result = array('userid'        => $userid,
                        'DocumentMaker' => $username,
                        'MakeDate'      => $makeDate,
                        'type'          => 'show'
                );
        $this->load->view("QualityAbnormal",$result);
    }
    public function Login(){
        if (isset($_GET['code'])){
            $code = $_GET['code'];
            //$res = $this->Data_model->get_single_data("name = '中兴精密'","WEIXININFO");
            $res = $this->Data_model->get_single_data(array("name" => "中兴精密",
                                                            "type" => 'QualityAbnormal_56'),"WEIXININFO");
            $this->get_userId($res['access_token'], $code,$res['agentid']);
        }else{
            echo "NO CODE";
        }
    }
    
    function get_userId($access_token,$code,$agentId){
        if($access_token){
            $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=".$access_token."&code=".$code."&agentid=".$agentId;
            $json=self::http_request_json($url);//这个地方不能用file_get_contents
            $data=json_decode($json,true);
            if(isset($data['errcode'])){
                if($data['errcode'] == "40001" or $data['errcode'] == '42001' or $data['errcode'] == '40014'){
                    $this->get_access_token();
                    $newurl = "<?=base_url()?>/QualityAbnormal/Login?code=".$code;
                    echo "<script language='javascript' type='text/javascript'>";  
                    echo "window.location.href='".$newurl."'";  
                    echo "</script>"; 
                    
                }else{
                    echo "页面请求错误，请检查！";
                }
            }else{
                $this->index($data['UserId']);
            }
        }else{
            $this->get_access_token();
            $this->getLoginInfo();
        }
    }
    function get_access_token(){
        $result = $this->Data_model->get_single_data(array("name" => "中兴精密",
                                                            "type" => 'QualityAbnormal_56'),"WEIXININFO");
        $corpid = $result['corpid'];
        $corpsecret = $result['corpsecret'];
        $url="https://qyapi.weixin.qq.com/cgi-bin/gettoken?&corpid=".$corpid."&corpsecret=".$corpsecret;
        $json=self::http_request_json($url);//这个地方不能用file_get_contents
        $data=json_decode($json,true);
        if(isset($data['access_token'])){
            $this->Data_model->update_data(array("name" => "中兴精密",
                                                            "type" => 'QualityAbnormal_56'),array('access_token' => $data['access_token']),'WEIXININFO');
        }else{
            return "获取access_token错误";
        }        
    }
    //因为url是https 所有请求不能用file_get_contents,用curl请求json 数据
    function http_request_json($url){  
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;  
    }
    function get_checkdata($date,$userid,$tablename){
        //$resData = $this->Data_model->get_single_data("CHECKDATE = '".$date."' and EMPNO = '".$userid."'",$tablename);
        $resData = $this->Data_model->get_data(array("CHECKDATE" => $date,
                                                        "EMPNO" => $userid),"","",-1,-1,$tablename);
        return $resData;
    }
    
    public function getUsername($userid){
        $res = $this->Data_model->get_single_data(array('name'=>'中兴精密',
                                                            'type'=>'QualityAbnormal_56'),"WEIXININFO");
        $url="https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=".$res['access_token']."&userid=".$userid;
            $json=self::http_request_json($url);//这个地方不能用file_get_contents
            $data=json_decode($json,true);
            return $data["name"];
    }
    function update(){
        header("Access-Control-Allow-Origin:*");
        $this->dbConnectsql = $this->load->database("sqlserver_hr",TRUE);
        $userno          = trim($_GET['userno']);
        $usertel         = trim($_GET['usertel']);
        $email           = trim($_GET['email']);
        $useraddress     = trim($_GET['useraddress']);
        $fatherName      = trim($_GET["fatherName"]);
        $fatherBirth     = trim($_GET['fatherBirth']);
        $motherName      = trim($_GET['motherName']);
        $motherBirth     = trim($_GET['motherBirth']);
        $tel             = trim($_GET['tel']);
        $address         = trim($_GET['address']);
        
        $query = $this->dbConnectsql->query("update A01 set A0222 = '$usertel',EMAIL = '$email',A0117 = '$useraddress',fatherName = '$fatherName',"
                . "fatherBirth = '$fatherBirth',motherName = '$motherName',motherBirth = '$motherBirth',tel = '$tel',address = '$address' where A0190 = '$userno'");
		//echo "update A01 set A0222 = '$usertel',EMAIL = '$email',A0117 = '$useraddress',fatherName = '$fatherName',"
        //        . "fatherBirth = '$fatherBirth',motherName = '$motherName',motherBirth = '$motherBirth',tel = '$tel',address = '$address' where A0190 = '$userno'";
	}
	function updateSuccess(){
		$userid = trim($_GET['userid']);
		$this->index($userid);
	}
        public function add(){
            header("Access-Control-Allow-Origin:*");
            $this->dbConnectsql = $this->load->database("sqlserver",TRUE);
            $MakeDate          = isset($_REQUEST['MakeDate'])?$_REQUEST['MakeDate']:'';
            $OccurDate         = isset($_REQUEST['OccurDate'])?$_REQUEST['OccurDate']:'';
            $WorkNO            = isset($_REQUEST['WorkNO'])?$_REQUEST['WorkNO']:'';
            $DocumentMaker     = isset($_REQUEST['DocumentMaker'])?$_REQUEST['DocumentMaker']:'';
            $ProductName       = isset($_REQUEST['ProductName'])?$_REQUEST['ProductName']:'';
            $PartsNO           = isset($_REQUEST['PartsNO'])?$_REQUEST['PartsNO']:'';
            $BadNum            = isset($_REQUEST['BadNum'])?$_REQUEST['BadNum']:'';
            $Responsible       = isset($_REQUEST['Responsible'])?$_REQUEST['Responsible']:'';
            $ProblemSolver     = isset($_REQUEST['ProblemSolver'])?$_REQUEST['ProblemSolver']:'';
            $ManPower          = isset($_REQUEST['ManPower'])?$_REQUEST['ManPower']:'';
            $Hours             = isset($_REQUEST['Hours'])?$_REQUEST['Hours']:'';
            $QualityAbnormal   = isset($_REQUEST['QualityAbnormal'])?$_REQUEST['QualityAbnormal']:'';
            $Remark            = isset($_REQUEST['Remark'])?$_REQUEST['Remark']:'';
            $Thumb             = isset($_REQUEST['Thumb'])?base_url()."html/image/QualityAbnormal/upload/".$_REQUEST['Thumb']:'';
            $BadNum            = empty($BadNum)?"0":$BadNum;
            $ManPower          = empty($ManPower)?"0":$ManPower;
            $Hours             = empty($Hours)?"0":$Hours;
            $userid            = isset($_REQUEST['userid'])?$_REQUEST['userid']:''; 
            $MakeDate = str_replace("-", "", $MakeDate);
            $OccurDate = str_replace("-", "", $OccurDate);
            $Monthly = substr($MakeDate, 0,6);
            $query = $this->dbConnectsql->query("select ID from WX_QUALITYABNORMAL where Monthly = $Monthly order by ID desc");
            $oldID = $query->row_array();
            $ID = $oldID['ID'] + 1;
            $OrderStr = "ZLYC".substr($MakeDate, 0,4).substr($MakeDate, 4,2);
            $OrderNO = $OrderStr.str_pad($ID, 5,"0",STR_PAD_LEFT);
            $query = $this->dbConnectsql->query("insert into WX_QUALITYABNORMAL (ID,OrderNO,MakeDate,OccurDate,WorkNO,ProductName,PartsNO,BadNum,DocumentMaker,QualityAbnormal,Thumb,ManPower,Hours,Remark,Responsible,ProblemSolver,Monthly) values "
                    . "('$ID','$OrderNO','$MakeDate','$OccurDate','$WorkNO','$ProductName','$PartsNO','$BadNum','$DocumentMaker','$QualityAbnormal','$Thumb','$ManPower','$Hours','$Remark','$Responsible','$ProblemSolver','$Monthly')");
            $res = array('orderno' => $OrderNO,'userid'=>$userid);
            echo json_encode($res);
        }
        
        public function SubmitSuccess(){
            $orderno = isset($_REQUEST['orderno'])?$_REQUEST['orderno']:'';
            $userid  = isset($_REQUEST['userid'])?$_REQUEST['userid']:'';
            $result = array(
                        'type'          => 'success',
                        'orderno'       => $orderno,
                        'userid'        => $userid,
                );
            $this->load->view("QualityAbnormal",$result);
        }
        
        public function back(){
            $userid = isset($_REQUEST['userid'])?$_REQUEST['userid']:'';
            $this->index($userid);
        }
}
